#!/usr/bin/python
# -*- coding:utf8 -*-
import MySQLdb
import ConfigParser
import os
import urllib2
import urllib
import sys


class CoinTools:
    def __init__(self):
        if os.path.exists('./config.ini'):
            self.cf = ConfigParser.ConfigParser()
            self.cf.read('./config.ini')
            self.init_cfg()

    def init_cfg(self):
        self.DB_HOST = self.cf.get('mysql', 'DB_HOST')
        self.DB_USER = self.cf.get('mysql', 'DB_USER')
        self.DB_PASSWD = self.cf.get('mysql', 'DB_PASSWD')
        self.DB_NAME = self.cf.get('mysql', 'DB_NAME')

    def mysqlconnect(self):
        """
        Return a MySQL database connection
        """
        try:
            conn = MySQLdb.connect(self.DB_HOST,
                                   self.DB_USER,
                                   self.DB_PASSWD,
                                   self.DB_NAME,
                                   charset="utf8",
                                   use_unicode=True)
            return conn
        except MySQLdb.Error, e:
            sys.stderr.write("Error %d: %s\n" % (e.args[0], e.args[1]))
            sys.exit(1)

    def secondts_2_mints(self, ts):
        '''
        秒级时间戳自动转成分钟时间戳取整
        :return:
        '''
        mod = ts % 60
        return ts - mod

    @staticmethod
    def doGet(url):
        try:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
            req = urllib2.Request(url=url, headers=headers)
            html = urllib2.urlopen(req, timeout=5).read()
            return html
        except Exception as e:
            print e

    def readini(self, section, option):
        return self.cf.get(section, option)


if __name__ == '__main__':
    pass
